import { defineStore } from "pinia";
import { ref } from "vue";
import {login, getUserInfo, logout, loginByPhone} from "@/common/net/api";
import router from "@/router";
import type { User, CodeUser } from "@/common/types/userType";
import { ElMessage } from "element-plus";

export const useUserStore = defineStore("user", () => {
  const token = ref<string | null>(localStorage.getItem("token") || null);
  const userInfo = ref<User | null>(null);

  /**
   * 处理登录逻辑
   * @param user - 用户信息（账号密码登录或手机号登录）
   */
  async function handleLogin(user: User | CodeUser) {
    try {
      // 调用登录接口
      const response = await login(user as any); // 适配后端接口
      console.log(response)
      if (response.data.state) {
        // 登录成功，保存 token
        localStorage.setItem("token", response.data.data as string);
        await fetchUserInfo(); // 获取用户信息
        ElMessage.success("登录成功！");
        router.push("/"); // 跳转到首页
      } else {
        // 登录失败，提示错误信息
        ElMessage.error(response.data.msg);
      }
    } catch (error: any) {
      ElMessage.error("登录失败：" + error.message);
    }
  }
  async function handleLoginByPhone(user: User | CodeUser) {
    try {
      // 调用登录接口
      const response = await loginByPhone(user as any); // 适配后端接口
      if (response.data.state) {
        // 登录成功，保存 token
        localStorage.setItem("token", response.data.data as string);
        await fetchUserInfo(); // 获取用户信息
        ElMessage.success("登录成功！");
        await router.push("/"); // 跳转到首页
      } else {
        // 登录失败，提示错误信息
        ElMessage.error(response.data.msg);
      }
    } catch (error: any) {
      ElMessage.error("登录失败：" + error.message);
    }
  }

  /**
   * 获取用户信息
   */
  async function fetchUserInfo() {
    if (token.value) {
      const info = await getUserInfo(token.value);
      if (info.data.state) {
        // @ts-ignore
        userInfo.value = info.data.data; // 保存用户信息
      } else {
        ElMessage.error(info.data.msg);
      }
    }
  }

  /**
   * 处理退出登录
   */
  async function handleLogout() {
    if (token.value) {
      const response = await logout(token.value);
      if (response.data.state) {
        // 清除本地存储和用户信息
        token.value = null;
        localStorage.removeItem("token");
        userInfo.value = null;
        router.push("/login"); // 跳转到登录页面
        ElMessage.success("退出成功！");
      } else {
        ElMessage.error(response.data.msg);
      }
    }
  }

  return { token, userInfo, handleLogin, fetchUserInfo, handleLogout,handleLoginByPhone };
});
